import {AXIOS} from '~/../config/axios.conf'
import {getUserInfo, getClassid} from '~/api'

// 初始化用户信息
export class InitUserInfo {
    store: any = null
    userInfo: any = null
    haslogin: boolean = false
    constructor (store: any) {
        this.store = store
        this.init()
    }
    async getUserInfo () {
        const res: any = await getUserInfo()
        if (res.data && res.data.code >= 0) {
            this.interceptorsAxios(res.data.data)
            this.store.commit('setUserInfo', res.data.data)
        }
        this.store.commit('setUserNum')
    }
    interceptorsAxios (userInfo: any) {
        const token = userInfo.uuid
        AXIOS.interceptors.request.use(
            (config) => {
                let isClient = false
                try {
                    if (window) {
                        isClient = true
                    }
                } catch (e) {}
                if (isClient && token) {
                    config.headers['x-ho-token'] = token
                    config.headers['x-ho-role'] = `${userInfo.id}_${userInfo.selectRoleType}_${userInfo.roleUserId}`
                } else {
                    delete config.headers['x-ho-token']
                    delete config.headers['x-ho-role']
                }
                return config
            },
            (err) => {
                return Promise.reject(err)
            }
        )
    }
    init () {
        this.userInfo = this.store.state.userinfo
        this.haslogin = this.store.state.haslogin
        if (!this.haslogin) {
            this.getUserInfo()
        } else {
            this.interceptorsAxios(this.userInfo)
        }
    }
}

export const setClassid = async (store: any, type:boolean) => {
    const sign = type ? 'community' : 'qiao'
    const mtd = type ? 'setClassid' : 'setTree'
    if (store.state[type ? 'classid' : 'tree'].length === 0) {
        const {data}: any = await getClassid(sign)
        if (data.flag) {
            store.commit(mtd, data.data)
        }
    }
}

// 打开53客服
export const open53Server = (k: string = '6ea5ef686e1e3682688ddc64d3c13328', wk: string = '2') => {
    const w: number = 800
    const h: number = 600
    const itop = (window.screen.height - 30 - h) / 2
    const ileft = (window.screen.width - 10 - w) / 2
    window.open(
        `https://tb.53kf.com/code/client/${k}/${wk}`,
        '',
        `width=${w},height=${h},top=${itop},left=${ileft},toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no`
    )
}
